package com.bristua.barcode.job;

import com.bristua.barcode.common.constants.Constants;
import com.bristua.barcode.supplier.dao.TChannelRequestConfigMapper;
import com.bristua.barcode.supplier.dao.TQrCodeCookieMapper;
import com.bristua.barcode.supplier.model.TChannelRequestConfig;
import com.bristua.barcode.supplier.model.TQrCodeCookie;
import com.bristua.barcode.supplier.model.condition.TChannelRequestConfigExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class KeyExpiredListener implements MessageListener {

    private final static Logger LOG = LoggerFactory.getLogger(KeyExpiredListener.class);

    @Resource
    private TQrCodeCookieMapper tQrCodeCookieMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private TChannelRequestConfigMapper tChannelRequestConfigMapper;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();// 请使用valueSerializer
        byte[] channel = message.getChannel();
//		String topic = new String(channel);
        String key = new String(body);
        if(key.contains(Constants.COOKIE_KEY)){
            key = key.substring(Constants.COOKIE_KEY.length(),key.length());

            TQrCodeCookie tQrCodeCookie = tQrCodeCookieMapper.selectByPrimaryKey(key);
            TChannelRequestConfigExample tChannelRequestConfigExample = new TChannelRequestConfigExample();
            tChannelRequestConfigExample.createCriteria().andChannelIdEqualTo(tQrCodeCookie.getChannelId());
            List<TChannelRequestConfig> tChannelRequestConfigs = tChannelRequestConfigMapper.selectByExample(tChannelRequestConfigExample);
            if(tChannelRequestConfigs!=null && tChannelRequestConfigs.size()>0){
                TChannelRequestConfig tChannelRequestConfig = tChannelRequestConfigs.get(0);
                HttpClientUtils.httpRequest(tChannelRequestConfig.getUrl(), tChannelRequestConfig.getParams(),tQrCodeCookie.getContent(), tChannelRequestConfig);
                redisTemplate.opsForValue().set(key,key,getRandom(), TimeUnit.MINUTES);
            }

        }

    }

    private int getRandom() {
        int[] arr = {1, 2, 3, 4, 5};
//产生0-(arr.length-1)的整数值,也是数组的索引
        int index = (int) (Math.random() * arr.length);
        return arr[index];
    }

    public static void main(String[] args) {
        String aa= "111111222";
        String a = aa+"SPPPPPPPPPPP";
        int i = a.lastIndexOf("123_123");
        String substring = a.substring(aa.length(), a.length());

        System.out.println(substring);
    }


}